/*
 * Copyright (c) 2019 Wormpex.com. All Rights Reserved.
 */

package com.sk.leetcode.arithmetic;

import java.util.concurrent.Semaphore;

/**
 * https://leetcode-cn.com/problems/print-foobar-alternately/
 *
 * @author ke.su date: 2019-09-23 Time: 下午5:51
 */
public class Test1115 {
    final Semaphore semaphore0 = new Semaphore( 99);
    final Semaphore semaphore1 = new Semaphore(100);
    private int n;

    public Test1115(int n) {

        this.n = n;
    }

    public static void main(String[] args) throws Exception{
         Semaphore semaphore0 = new Semaphore( 4);
         Semaphore semaphore1 = new Semaphore(5);

        Thread t1 = new Thread(() -> {
            for(int i = 0; i < 5; i++){
                if (i != 0) {
//                    try {
//                        //semaphore0.acquire(11);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                }
                System.out.print("foo");
                //semaphore1.release();
            }

        });
        Thread t2 = new Thread(() -> {
            for(int i = 0; i < 5; i++){
                try {
                    System.out.println(i);
                    semaphore1.acquire(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.print("bar");
               // semaphore0.release();
            }
        });

        t1.start();
        t2.start();


    }

    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            if (i != 0) {
                semaphore0.acquire();
            }
            // printFoo.run() outputs "foo". Do not change or remove this line.
            printFoo.run();
            semaphore1.release();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            semaphore1.acquire();
            // printBar.run() outputs "bar". Do not change or remove this line.
            printBar.run();
            semaphore0.release();
        }
    }

}
